package pers.qianyu.month_202012.date_20201205;

import java.util.*;

/**
 * 46. LRU 缓存机制
 * https://leetcode-cn.com/problems/lru-cache/
 *
 * @author mizzle rain
 * @date 2020-12-05 22:12
 */
public class LRUCache {
    private LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>();
    private int cap;

    public LRUCache(int capacity) {
        this.cap = capacity;
    }

    public int get(int key) {
        if (map.containsKey(key)) {
            Integer value = map.get(key);
            map.remove(key);
            map.put(key, value);
            return value;
        }
        return -1;
    }

    public void put(int key, int value) {
        if (map.containsKey(key)) {
            map.remove(key);
            map.put(key, value);
            return;
        }
        map.put(key, value);
        if (map.size() > cap) {
            removeHead();
        }
    }

    private void removeHead() {
        Integer next = map.keySet().iterator().next();
        map.remove(next);
    }
}
